﻿@model SealManagement.Models.ProduceSign
@{
    ViewData["Titel"] = "制章";
}

<h2 style="margin:20px 0">制章</h2>
<hr />
<div class="form-group">
    <div class="col-md-offset-1 col-md-10 ">
        <form class="form-horizontal">
            <div class="form-group">
                <label for="sealName" class="col-sm-2 control-label">印章名称</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="sealName">
                </div>
            </div>

            <div class="form-group">
                <label for="sealType" class="col-sm-2 control-label">印章类型</label>
                <div class="col-sm-10" id="typeValue ">
                    <select id="sealType" name="sealType" class="form-control">
                        <option value="">请选择</option>
                        <option value="1">单位印章</option>
                        <option value="2">个人印章</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="sealStartTime" class="col-sm-2 control-label">印章生效时间</label>
                <div class="col-sm-10">
                    <input type="date" class="form-control" id="sealStartTime"/>
                </div>
            </div>
            <div class="form-group">
                <label for="sealEndTime" class="col-sm-2 control-label">印章作废时间</label>
                <div class="col-sm-10">
                    <input type="date" class="form-control" id="sealEndTime" />
                </div>
            </div>
            <input id="makerCertID" type="hidden" value="@ViewBag.makerArrayNo" class="form-control" />
            <div class="form-group">
                <label class="col-sm-2 control-label">用户UKEY</label>
                <div class="col-sm-10" style="line-height: 30px;">
                    <select id="userCertID" name="ukeySelect" class="form-control"></select>
                </div>
            </div>
            
            <div class="form-group">
                <label class="control-label col-md-2">印章图片</label>
                <div class="col-md-10">
                    <input type="hidden" id="picBase64" readonly="readonly" /><br />
                    <img id="pic" src="" style="max-width: 100%; border: 1px solid gray;" />
                </div>
            </div>
            <div class="form-group">
                <label class="control-label col-md-2">生成方式</label>
                <div class="col-md-10">
                    <div class="form-inline">
                        <input type="radio" name="picGenerateType" checked="checked" value="自动生成" />
                        <input type="button" id="generate" value="自动生成" class="btn btn-default" />
                    </div>
                    <br />
                    <div class="form-inline">
                        <input type="radio" name="picGenerateType" value="手动上传" />
                        <input type="file" name="upimage" id="upload_file" disabled="disabled" class="form-control" style="max-width: 260px" />
                    </div>
                </div>
            </div>
            <input type="hidden" id="sealBase64" />
            <input type="hidden"  id="sealHashBase64" />
            <input type="hidden" id="sealSigBase64" />
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <input id="btnCreate" type="button" value="创建" class="btn btn-default" />
                </div>
            </div>
        </form>
        <dl id="infoDiv" class="dl-horizontal" style="display: none">
        </dl>
    </div>
</div>

<div id="layerPagePinCode" style="display: none">
    <div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">
        请输入制章人PIN码：<br />
        <input type="password" name="ukeyPinCode" class="form-control" />
        <span id="pinError"></span>
    </div>
</div>


@section scripts {
    <script src="/Content/layui/layui.js" charset="utf-8"></script>
    <script src="~/js/dateformat.js"></script>
    <script>
        function EnumKey(funcBack, errorCallBack) {
            var socket = new WebSocket("ws://127.0.0.1:2012/CertInfo");
            try {
                socket.onerror = errorCallBack;
                socket.onopen = function (msg) {

                    //alert("连接成功！");
                    socket.send("abc");
                };
                socket.onmessage = function (e) {
                    if (isNumber(e.data)) {
                        funcBack("");
                    } else {
                        //alert(e.data);
                        funcBack(e.data);
                    }
                };
            }
            catch (ex) {
                funcBack("");
            }
        }
        function GetCertAndSeal(certSN, funcBack) {
            //alert(certSN);
            var dtd = $.Deferred();
            var socket = new WebSocket("ws://127.0.0.1:2012/SealAndCertBase64");
            try {
                socket.onopen = function(msg) {
                    //alert("连接成功！");
                    socket.send(certSN);
                };
                socket.onmessage = function(e) {
                    funcBack(e.data);
                    socket.close();
                    dtd.resolve();
                };
            } catch (ex) {
                funcBack("");
                socket.close();
            } finally {
                return dtd.promise();
            }
        }
        function SignByHash(strJson, funcBack) {

            //alert(strJson);
            var socket = new WebSocket("ws://127.0.0.1:2012/SignDataEx");
            try {

                socket.onopen = function (msg) {

                    //alert("连接成功！");
                    socket.send(strJson);
                };
                socket.onmessage = function (e) {
                    funcBack(e.data);
                    socket.close();
                };
            }
            catch (ex) {
                funcBack("");
                socket.close();
            }

        }
        function VerifyPin(strJson, funcBack) {

            //alert(strJson);
            var socket = new WebSocket("ws://127.0.0.1:2012/VerifyPin");
            try {

                socket.onopen = function (msg) {

                    //alert("连接成功！");
                    socket.send(strJson);
                };
                socket.onmessage = function (e) {
                    funcBack(e.data);
                    socket.close();
                };
            }
            catch (ex) {
                funcBack("");
                socket.close();
            }

        }
        
        function GetAuth(strJson, funcBack) {

            //alert(strJson);
            var socket = new WebSocket("ws://127.0.0.1:2012/Auth");
            try {

                socket.onopen = function (msg) {

                    //alert("连接成功！");
                    socket.send(strJson);
                };
                socket.onmessage = function (e) {
                    funcBack(e.data);
                    socket.close();
                };
            }
            catch (ex) {
                funcBack("");
                socket.close();
            }

        }
        function GetSerialId(certSN, funcBack) {
            var socket = new WebSocket("ws://127.0.0.1:2012/SerialId");
            try {

                socket.onopen = function (msg) {
                    socket.send(certSN);
                };
                socket.onmessage = function (e) {
                    funcBack(e.data);
                    socket.close();
                };
            }
            catch (ex) {
                funcBack("");
                socket.close();
            }

        }
        function GetProducts(certSN, funcBack) {
            var socket = new WebSocket("ws://127.0.0.1:2012/Products");
            try {

                socket.onopen = function (msg) {
                    socket.send(certSN);
                };
                socket.onmessage = function (e) {
                    funcBack(e.data);
                    socket.close();
                };
            }
            catch (ex) {
                funcBack("");
                socket.close();
            }
        }

        function GeneratePic(certID, funcBack) {

            //alert(strJson);
            var socket = new WebSocket("ws://127.0.0.1:2012/GeneratePic");
            try {

                socket.onopen = function (msg) {
                    socket.send(certID);
                };
                socket.onmessage = function (e) {
                    funcBack(e.data);
                    socket.close();
                }
            }
            catch (ex) {
                funcBack("");
                socket.close();
            }
        }

        function initlist(str) {
            $("select[name='ukeySelect']").each(function (index, element) {
                if (str == "") {
                    $(element).empty();
                }
                var certList = $.parseJSON(str);
                var selObj = $(element);
                var maxIndex = $(element).find("option:last").index(); //获取Select最大的索引值
                //alert(maxIndex);
                for (var i = maxIndex; i >= 0; i--) {
                    //alert(i);
                    var exsitFlag = false;
                    var currentValue = $(element).find("option:eq(" + i + ")").val();
                    for (var j = 0; j < certList.CertInfolist.length; j++) {
                        if (currentValue == certList.CertInfolist[j].CertID) {
                            exsitFlag = true;
                            break;
                        }
                    }
                    if (exsitFlag == false) {
                        $(element).find("option:eq(" + i + ")").remove();
                    }
                }
                for (var i = 0; i < certList.CertInfolist.length; i++) {
                    if ($(element).find("option[value='" + certList.CertInfolist[i].CertID + "']").index() == -1) {
                        selObj.append("<option value='" + certList.CertInfolist[i].CertID + "'>" + certList.CertInfolist[i].CertCN + "</option>");
                    }
                }

            });
            //$("select[name='ukeyUserSelect']").each(function (index, element) {
            //    if (str == "") {
            //        $(element).empty();
            //    }
            //    var certList = $.parseJSON(str);
            //    var selObj = $(element);
            //    var maxIndex = $(element).find("option:last").index(); //获取Select最大的索引值
            //    //alert(maxIndex);
            //    for (var i = maxIndex; i >= 0; i--) {
            //        //alert(i);
            //        var exsitFlag = false;
            //        var currentValue = $(element).find("option:eq(" + i + ")").val();
            //        for (var j = 0; j < certList.CertInfolist.length; j++) {
            //            if (currentValue == certList.CertInfolist[j].CertID) {
            //                exsitFlag = true;
            //                break;
            //            }
            //        }
            //        if (exsitFlag == false) {
            //            $(element).find("option:eq(" + i + ")").remove();
            //        }
            //    }
            //    for (var i = 0; i < certList.CertInfolist.length; i++) {
            //        if ($(element).find("option[value='" + certList.CertInfolist[i].CertID + "']").index() == -1) {
            //            selObj.append("<option value='" + certList.CertInfolist[i].CertID + "'>" + certList.CertInfolist[i].CertCN + "</option>");
            //        }
            //    }
            //});
        }
        function myPost(url, args) {
            var body = $(document.body),
                form = $("<form method='post'></form>"),
                input;
            form.attr({ "action": url });
            $.each(args, function (key, value) {
                input = $("<input type='hidden'>");
                input.attr({ "name": key });
                input.val(value);
                form.append(input);
            });

            form.appendTo(document.body);
            form.submit();
            document.body.removeChild(form[0]);
        }
        function isNumber(val) {

            var regPos = /^\d+(\.\d+)?$/; //非负浮点数
            var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
            if (regPos.test(val) || regNeg.test(val)) {
                return true;
            } else {
                return false;
            }
        }
        function DisplayMessage(message) {
            var mydate = new Date();
            $("#infoDiv").append("<dt>" +
                mydate.Format("hh:mm:ss") +
                "</dt><dd>" +
                message +
                "</dd>");
        }
        
        
        //计算印章哈希
        
        function ComputeSealHash() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/ComputeSealHash";
            var socket = new WebSocket(uri);
            // 建立 web socket 连接成功触发事件
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    makerCertID: $("#makerCertID").val(),
                    userCertID: $("#userCertID").val(),
                    picBase64: $("#picBase64").val(),
                    sealName: $("#sealName").val(),
                    sealType: $("#sealType").val(),
                    sealStartTime: $("#sealStartTime").val(),
                    sealEndTime: $("#sealEndTime").val()
                };
                // 使用 send() 方法发送数据
                socket.send(JSON.stringify(data));
            };
            // 断开 web socket 连接成功触发事件
            socket.onclose = function (e) { console.log("closed"); };
            // 接收服务端数据时触发事件socket.close();
            socket.onmessage = function (e) {
                console.log(e.data);
                var retJSONObject = JSON.parse(e.data);
                if (retJSONObject.error == "Ok") {
                    $("#sealBase64").val(retJSONObject.sealBase64);
                    $("#sealHashBase64").val(retJSONObject.digestBase64);
                    dtd.resolve();
                }
                socket.close();
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        //计算印章签名
        function ComputeSealSig() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/SignDataEx";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    certId: $("#makerCertID").val(),
                    hashBase64: $("#sealHashBase64").val(),
                    strPin: "111111"
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(e.data);
                var retJSONObject = JSON.parse(e.data);
                if (retJSONObject.error == "Ok") {
                    $("#sealSigBase64").val(retJSONObject.SigBase64);
                    dtd.resolve(e.data);
                }
                socket.close();
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        //计算最终印章数据
        function ComputeSeal() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/ComputeSeal";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    sealWithoutSigBase64: $("#sealBase64").val(),
                    sigBase64: $("#sealSigBase64").val()
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(e.data);
                var retJSONObject = JSON.parse(e.data);
                if (retJSONObject.error == "Ok") {
                    $("#sealBase64").val(retJSONObject.sealBase64);
                    dtd.resolve();
                }
                socket.close();
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        //写入印章数据
        function WriteUkey() {
            var dtd = $.Deferred();
            var uri = "ws://127.0.0.1:2012/WriteUkey";
            var socket = new WebSocket(uri);
            socket.onopen = function (e) {
                console.log("connected");
                var data = {
                    certID: $("#userCertID").val(),
                    fileName: "GBESEAL",
                    dataBase64: $("#sealBase64").val()
                };
                socket.send(JSON.stringify(data));
            };
            socket.onclose = function (e) { console.log("closed"); };
            socket.onmessage = function (e) {
                console.log(e.data);
                if (e.data == "Ok") {
                    dtd.resolve();
                }
                socket.close();
            };
            socket.onerror = function (e) { console.log("Error: " + e.data); };
            return dtd.promise();
        }
        var layer = null;
        layui.use('layer',
            function() {
                layer = layui.layer;
            });
        $(function () {
            EnumKey(function(data) {
                    initlist(data);
                },
                function() {
                    layer.alert("未安装UKEY支持服务！");
                });
            $("input[name='picGenerateType']").click(function () {
                var picGenerateType = $("input[name='picGenerateType']:checked").val();
                if (picGenerateType == "自动生成") {
                    $("#generate").attr("disabled", false);
                    $("#upload_file").attr("disabled", true);
                } else {
                    $("#generate").attr("disabled", true);
                    $("#upload_file").attr("disabled", false);
                }
            });
            $("#generate").click(function () {
                var certSN = $("#userCertID").val();
                GeneratePic(certSN,
                    function (value) {
                        var retJObject = JSON.parse(value);
                        if (retJObject.error == "Ok") {
                            var picBase64 = retJObject.picBase64;
                            $("#pic").attr("src", "data:image/png;base64," + picBase64);
                            $("#picBase64").val(picBase64);
                        }
                    });
            });
            $("#upload_file").change(function () {
                var file = $('#upload_file').get(0).files[0];
                if (!/image\/\w+/.test(file.type)) {
                    layer.alert("请确保文件为图像类型");
                    return;
                }
                var r = new FileReader();  //本地预览
                r.onload = function() {
                    $("#pic").attr("src", r.result);
                    $("#picBase64").val(r.result.substring(r.result.indexOf(',') + 1));
                };
                r.readAsDataURL(file);    //Base64
            });
            $('#btnCreate').click(function () {
                $("#infoDiv").empty();
                $("#infoDiv").fadeIn();
                $("#btnCreate").attr("disabled", true);
                DisplayMessage("正在获取UKEY证书");
                if ($("#makerCertID").val() == $("#userCertID").val()) {
                    DisplayMessage("制章人UKEY与用户UKEY不能为同一个");
                    $("#btnCreate").attr("disabled", false);
                    return;
                }
                console.log($("#makerCertID").val());
                console.log($("#userCertID").val());
                var makerCertBase64 = "";
                var userCertBase64 = "";
                var certSN = $("#makerCertID").val();
                var dtd1 = GetCertAndSeal(certSN, function (certAndSeal) {
                    console.log(certSN);
                    console.log(certAndSeal);
                    var certAndSealJObject = JSON.parse(certAndSeal);
                    if (certAndSealJObject.CertBase64.length != 0) {
                        makerCertBase64 = certAndSealJObject.CertBase64;
                    }
                });
                var certUserSN = $("#userCertID").val();
                var dtd2 = GetCertAndSeal(certUserSN, function (certAndSeal) {
                    var certAndSealJObject = JSON.parse(certAndSeal);
                    if (certAndSealJObject.CertBase64.length != 0) {
                        userCertBase64 = certAndSealJObject.CertBase64;
                    }
                });
                DisplayMessage("正在验证PIN码");
                var dtd = $.Deferred();
                $.when(dtd1, dtd2).done(function () {
                    if (makerCertBase64 == "") {
                        DisplayMessage("未插入制章人UKEY，无法完成操作");
                        return;
                    }
                    layer.open({
                        type: 1
                        , title: false //不显示标题栏
                        , closeBtn: true
                        , area: '300px;'
                        , shade: 0.8
                        , id: 'LAY_InputPin' //设定一个id，防止重复弹出
                        , btn: ['确定']
                        , btnAlign: 'c'
                        , moveType: 1 //拖拽模式，0或者1
                        , content: $("#layerPagePinCode").html(),
                        yes: function (index, layero) {
                            VerifyPin(JSON.stringify({
                                    CertID: certSN,
                                    Pin: layero.find("input[name='ukeyPinCode']").val()
                                }),
                                function(verifyPinRet) {
                                    if (verifyPinRet != "Ok") {
                                        layero.find("#pinError").html("Pin码错误，请重新输入");
                                        layero.find("input[name='ukeyPinCode']").val("");
                                    } else {
                                        $("input[name='ukeyPinCode']")
                                            .val(layero.find("input[name='ukeyPinCode']").val());
                                        layer.close(index);
                                        dtd.resolve();
                                    }
                                });
                        }
                    });
                });
                DisplayMessage("正在制章...");
                dtd.done(function() {
                    ComputeSealHash().done(function() {
                        ComputeSealSig().done(function() {
                            ComputeSeal().done(function () {
                                WriteUkey().done(function() {
                                    var data = {
                                        sealName: $("#sealName").val(),
                                        sealType: $("#sealType").val(),
                                        startTime: $("#sealStartTime").val(),
                                        endTime: $("#sealEndTime").val(),
                                        makerCertSN: certSN,
                                        makerCertBase64: makerCertBase64,
                                        userCertSN: certUserSN,
                                        userCertBase64: userCertBase64,
                                        sealBase64: $("#sealBase64").val()
                                    };
                                    $.post("/ProduceSign/Create",
                                        data,
                                        function (ret) {
                                            DisplayMessage("制章成功");
                                            console.log(ret);
                                        });
                                    $("#btnCreate").attr("disabled", false);
                                });
                            });
                        });
                    });
                });

                //var ArrayNo = $('#ArrayNo').val();
                //var Certificator = $('#Certificator').val();
                //var Remark = $('#Remark').val();
                //var ukeySelect = $('#ukeySelect').val();


                //var ukeyInput =
                //{
                //    ArrayNo: ArrayNo,
                //    Certificator: Certificator,
                //    sealHashBase64: sealHashBase64,
                //    Remark: Remark,
                //    ukeySelect: ukeySelect
                //};
                //DisplayMessage("正在向服务器发送验证数据");
                //myPost("/Login/SignMakerLogin", ukeyInput);

            });
        });
    </script>
}
